package com.shayu.aicodemother.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.shayu.aicodemother.constant.UserConstant;
import com.shayu.aicodemother.exception.BusinessException;
import com.shayu.aicodemother.exception.ErrorCode;
import com.shayu.aicodemother.model.dto.user.UserLoginRequest;
import com.shayu.aicodemother.model.dto.user.UserQueryRequest;
import com.shayu.aicodemother.model.entity.User;
import com.shayu.aicodemother.mapper.UserMapper;
import com.shayu.aicodemother.model.enums.UserRoleEnum;
import com.shayu.aicodemother.model.vo.LoginUserVO;
import com.shayu.aicodemother.model.vo.UserVO;
import com.shayu.aicodemother.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 用户 服务层实现。
 *
 * @author <a href="https://so.gitee.com/?q=%E8%8E%8E%E5%A3%AB%E6%AF%94%E8%B0%AD">程序员鲨鱼</a>
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    /**
     * 账号注册
     *
     * @param userAccount   账号
     * @param userPassword  密码
     * @param checkPassword 校验密码
     * @return
     */
    @Override
    public Long UserRegister(String userAccount, String userPassword, String checkPassword) {
        //1.校验
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "输入的两次密码不匹配");
        }

        //2.数据库是否存在
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount", userAccount);
        User user = this.getOne(queryWrapper);
        if (user != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }

        //3.密码加密
        String encryPassword = getEncryPassword(userPassword);

        //4.插入数据库
        User User = new User();
        User.setUserAccount(userAccount);
        User.setUserPassword(encryPassword);
        User.setUserRole(UserRoleEnum.USER.getValue());
        User.setUserName("无名");
        boolean save = this.save(User);
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "注册失败，数据库错误");
        }

        return User.getId();
    }


    /**
     * 密码加密
     *
     * @param userPassword
     * @return
     */
    @Override
    public String getEncryPassword(String userPassword) {
        //盐值，混淆密码
        final String name = "shayu";
        return DigestUtils.md5DigestAsHex((name + userPassword).getBytes());
    }


    /**
     * 账号登录
     *
     * @param userLoginRequest
     * @return
     */
    @Override
    public LoginUserVO userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        //1.校验
        if (StrUtil.hasBlank(userLoginRequest.getUserAccount(), userLoginRequest.getUserPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请填写账号密码");
        }
        if (userLoginRequest.getUserAccount().length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userLoginRequest.getUserPassword().length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }

        //2.加密
        String encryPassword = getEncryPassword(userLoginRequest.getUserPassword());

        //3.比对
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount", userLoginRequest.getUserAccount());
        queryWrapper.eq("userPassword", encryPassword);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或者密码错误");
        }
        //4.记录登录的用户状态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);

        //5.返回脱敏数据
        return this.getLoginUserVO(user);
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }

        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }


    /**
     * 通过Session获取用户消息
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (user == null || user.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        //从数据库中查找
        Long userId = user.getId();
        user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return user;
    }


    /**
     * 注销
     *
     * @param request
     * @return
     */
    @Override
    public Boolean userLoginout(HttpServletRequest request) {
        //先判断是否已登录
        Object userobj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (userobj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }
        //移除登录
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    @Override
    public UserVO getUserVo(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;

    }


    /**
     * 返回querywrapper对象
     *
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper getQueryRequest(UserQueryRequest userQueryRequest) {
        if (userQueryRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }

            Long id = userQueryRequest.getId();
            String userAccount = userQueryRequest.getUserAccount();
            String userName = userQueryRequest.getUserName();
            String userProfile = userQueryRequest.getUserProfile();
            String userRole = userQueryRequest.getUserRole();
            String sortField = userQueryRequest.getSortField();
            String sortOrder = userQueryRequest.getSortOrder();
            return QueryWrapper.create()
                    .eq("id", id)
                    .eq("userRole", userRole)
                    .like("userAccount", userAccount)
                    .like("userName", userName)
                    .like("userProfile", userProfile)
                    .orderBy(sortField, "ascend".equals(sortOrder));
        }


    /**
     * 转换成脱敏用户列表数据
     *
     * @param records
     * @return
     */
    @Override
    public List<UserVO> getUserVoList(List<User> records) {

        if (CollUtil.isEmpty(records)) {
            return new ArrayList<>();
        }
        List<UserVO> userVOList = records.stream().map(this::getUserVo).collect(Collectors.toList());
        return userVOList;
    }
}
